package com.cold.legendary.bprocess.trigger.impl;

import com.alibaba.fastjson.JSON;
import com.cold.legendary.bprocess.context.ins.BPointIns;
import com.cold.legendary.bprocess.context.run.BContext;
import com.cold.legendary.bprocess.db.enums.PointRunStatusEnum;
import com.cold.legendary.bprocess.db.model.TbProcessRequest;
import com.cold.legendary.bprocess.definition.point.BPointService;
import com.cold.legendary.bprocess.trigger.AbstractBProcessTriggerService;
import com.cold.legendary.bprocess.trigger.enums.TriggerModeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author cold
 * @since 2023/3/10
 */
@Slf4j
@Service
public class InterruptBProcessTriggerService extends AbstractBProcessTriggerService {
    @Override
    public void triggerBPoint(BPointIns triggerBPointIns, BContext bContext) {
        try {
            //校验流程请求
            TbProcessRequest qryProcessRequest = processRequestCheckHelper.checkProcessRequest(bContext);
            //基础业务校验
            baseCheck(bContext, triggerBPointIns, qryProcessRequest);

            if (PointRunStatusEnum.FINISH.getCode().equals(qryProcessRequest.getPointRunStatus())) {
                log.info("此节点已结束!无需触发中断!bizId={}, merchantId={},processId={}",
                        bContext.getBizId(), bContext.getMerchantId(), bContext.getProcessId());
                return;
            }
            //执行中断节点业务逻辑
            log.info("<interrupt>-开始...triggerBPointId={}, bContext={}", triggerBPointIns.getPointId(), JSON.toJSONString(bContext));
            BPointService bPointService = triggerBPointIns.getBPointService();
            bPointService.interrupt(bContext);
            log.info("<interrupt>-结束...triggerBPointId={}, bContext={}", triggerBPointIns.getPointId(), JSON.toJSONString(bContext));

            //中断流程数据变更
            bProcessTransactionService.interrupt(bContext, triggerBPointIns.getPointId());
        } catch (Exception e) {
            log.error("中断节点逻辑发生异常!", e);
        }
    }


    @Override
    protected TriggerModeEnum getTriggerModeEnum() {
        return TriggerModeEnum.INTERRUPT;
    }
}
